package ru.ognick.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import ru.ognick.locale.ILocale;
import ru.ognick.locale.ILocale.Lang;

public class Conf {

	private ILocale.Lang lang = Lang.EN;
	private File lastTraing = null;
	
	private static Conf _instance = null;
	
	private static Conf get() {
		if (_instance == null)
			_instance = load();
		return _instance;
	}
	
	public static ILocale.Lang getLang() {
		return get().lang;
	}
	public static void setLang(ILocale.Lang lang) {
		get().lang = lang;
		get().save();
	}
	public static File getLastTraing() {
		return get().lastTraing;
	}
	public static void setLastTraing(File lastTraing) {
		get().lastTraing = lastTraing;
		get().save();
	}
	
	public void save() {
	    final Gson gson = new GsonBuilder().create();
        final String jString = gson.toJson(this); 
        final File file = new File("self.conf");
        try {
  			file.createNewFile();
            final FileOutputStream fos = new FileOutputStream(file);
        	fos.write(jString.getBytes());
        	fos.close();
        } catch (IOException e) {
        	Log.e(this.getClass().getName(),e.getMessage());
        }
	}
	
	public static Conf load() {
    	File file = new File("self.conf");
		try {
			JSONArray j = new JSONArray(FileManager.asString(file));
	        Gson gson = new GsonBuilder().create();
	 		return gson.fromJson(j.toString(), Conf.class);
		} catch (JSONException e) {
			Log.e(Conf.class.getName(),e.getMessage());
		} catch (IOException e) {
			Log.e(Conf.class.getName(),e.getMessage());
		}
		return new Conf();
	}

}
